package com.ca.ridersclubapplication;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ca.ridersclubapplication.util.KeyBoardUtil;

public abstract class ImmersiveActivity extends AppCompatActivity {

    //  是否开启键盘自动收起
    public boolean enable = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //  设置沉浸式状态栏
        setStatusBarTextColor(Color.TRANSPARENT, true);
    }

    protected void setStatusBarTextColor(int backgroundColor, boolean light) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().setStatusBarColor(backgroundColor);
            int value = light ? View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | value);
        }
    }



    /**
     * 捕获用户触摸操作，如果不是输入框，则输入框自动失去焦点，并收起软键盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (enable && ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                //  如果视图为输入框，则失去焦点，并收起软键盘
                KeyBoardUtil.closeKeyBoard(this, view);
            }
        }

        return super.dispatchTouchEvent(ev);
    }


    /**
     * 判定是否需要隐藏
     */
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            return !(ev.getX() > left) || !(ev.getX() < right) || !(ev.getY() > top) || !(ev.getY() < bottom);
        }
        return false;
    }
}